'use strict'

const { Controller } = require('egg')
const axios = require('axios')
const clientID =
  '2edd1aac8f7f1752f39f88b02ce352469f181a47f504e7b0cb7b25f4374bb4cf'
const clientSecret =
  '84186718c115efd7709950caec921f022f5f45a280291d45713df9074ada0b88'
const redirect_uri = 'http://localhost:7001/api/oauth/redirect'
class LoginController extends Controller {
  async index() {
    const { ctx, app } = this
    const client1 = await app.mysql.get('users', { id: 2 })
    // await client1.query(sql, values)
    ctx.body = {
      code: 0,
      msg: 'success',
      data: client1,
    }
  }

  async oAuth() {
    const { ctx } = this
    const code = ctx.request.query.code
    console.log('authorization code:', code)
    const data = {
      code,
      redirect_uri,
      grant_type: 'authorization_code',
      client_id: clientID,
      client_secret: clientSecret,
    }
    const response = await axios.post(`https://gitee.com/oauth/token?`, data)
    console.log('response:', response.data.access_token)
    const access_token = response.data.access_token

    const res = await axios.get(
      `https://gitee.com/api/v5/user?access_token=${access_token}`
    )

    const { avatar_url, name } = res.data
    ctx.response.redirect(
      `http://localhost:8080/home?name=${name}&image=${avatar_url}`
    )
  }
}

module.exports = LoginController
